package com.xygj.vueblog.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class MyHttpRequest extends HttpServletRequestWrapper {

    private HttpServletRequest req;  // 原始请求对象
    private String encoding;  // 编码格式
    private boolean flag = true;  // 开关

    public MyHttpRequest(HttpServletRequest request) {
        super(request);

        this.req = request;
        this.encoding = encoding;
    }

    @Override
    public String getParameter(String name) {

        Map<String, String[]> map = getParameterMap();
        String[] values = map.get(name);
        if (null == values) {
            return null;
        }
        return values[0];
    }

    @Override
    public String[] getParameterValues(String name) {

        Map<String, String[]> map = getParameterMap();
        return map.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {

        String method = req.getMethod();

        if (method.equalsIgnoreCase("post")) {

            try {
                req.setCharacterEncoding(encoding);
                return req.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (method.equalsIgnoreCase("get") && true == flag) {

            // 通过flag使这段代码一次请求只执行一次，因为执行多次相当于解码再编码多次，造成乱码
            Map<String, String[]> map = req.getParameterMap();  // 对象赋值传递的是地址，map指向req地址，修改map值相当于修改req中属性值
            Set<String> set = map.keySet();
            // 迭代遍历map中所有值，通过解码再编码解决get乱码
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String[] values = map.get(iterator.next());
                if (null != values) {
                    for (int i = 0; i < values.length; i++) {
                        try {
                            values[i] = new String(values[i].getBytes("ISO-8859-1"), encoding);

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }

            flag = false;
            return map;
        }

        // 其它请求执行原始获取参数方法，除了get post外还有其他请求方式
        return super.getParameterMap();
    }
}
